const http = require('http');
const url = require('url');
const mongoose = require('mongoose');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');

// MongoDB连接
mongoose.connect('mongodb://127.0.0.1:27017/green_planet');

// 用户模型定义
const userSchema = new mongoose.Schema({
    username: String,
    email: { type: String, unique: true },
    password: String,
    carbonFootprint: Number,
    greenEnergy: Number,
    achievements: Array,
    tasks: Array,
    createdAt: { type: Date, default: Date.now }, // 添加创建时间字段
    planetState: {
        pollution: Number,
        biodiversity: Number,
        energy: {
            clean: Number,
            total: Number
        },
        buildings: Array,
        trees: Number,
        waterQuality: Number
    }
});

const User = mongoose.model('User', userSchema);

// 任务模型定义
const taskSchema = new mongoose.Schema({
    title: String,
    description: String,
    type: String,
    reward: {
        greenEnergy: Number,
        carbonReduction: Number
    },
    progress: { type: Number, default: 0 },
    criteria: {
        type: String,
        target: Number,
        current: Number
    },
    category: String
});

const Task = mongoose.model('Task', taskSchema);

// 在创建Task模型后添加CompletedTask模型
const completedTaskSchema = new mongoose.Schema({
    title: String,
    description: String,
    category: String,
    userId: String,
    reward: {
        greenEnergy: Number,
        carbonReduction: Number,
        waterQuality: Number
    },
    finishAt: Date
});

// 修改这行，第一个参数改为 'CompleteTask'，第三个参数指定实际的集合名称
const CompleteTask = mongoose.model('CompleteTask', completedTaskSchema, 'completeTasks');

// JWT密钥
const JWT_SECRET = 'your-secret-key';

// 添加异步处理函数
async function handleCompletedTasks(req, res) {
    try {
        const parsedUrl = url.parse(req.url, true);
        const userId = parsedUrl.query.userId;
        
        if (!userId) {
            res.writeHead(400, { 'Content-Type': 'application/json' });
            res.end(JSON.stringify({ error: '缺少用户ID参数' }));
            return;
        }

        // 根据userId查询该用户的已完成任务
        const completedTasks = await CompleteTask.find({ userId })
            .sort({ finishAt: -1 });
            
        console.log('已完成任务:', completedTasks);
        res.writeHead(200, { 'Content-Type': 'application/json' });
        res.end(JSON.stringify(completedTasks));
    } catch (error) {
        console.error('获取已完成任务失败:', error);
        res.writeHead(500, { 'Content-Type': 'application/json' });
        res.end(JSON.stringify({ error: '获取已完成任务失败' }));
    }
}

// 创建服务器
const server = http.createServer(async (req, res) => {
    // 设置CORS头
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
    res.setHeader('Access-Control-Allow-Headers', 'Content-Type');

    // 处理OPTIONS请求
    if (req.method === 'OPTIONS') {
        res.writeHead(200);
        res.end();
        return;
    }

    const parsedUrl = url.parse(req.url, true);

    // 处理已完成任务请求
    if (parsedUrl.pathname === '/api/tasks/completed') {
        await handleCompletedTasks(req, res);
        return;
    }

    // 处理登录请求
    if (parsedUrl.pathname === '/api/auth/login' && req.method === 'POST') {
        let body = '';
        req.on('data', chunk => {
            body += chunk.toString();
        });

        req.on('end', async () => {
            try {
                const { email, password } = JSON.parse(body);

                // 查找用户
                const user = await User.findOne({ email });
                if (!user) {
                    res.writeHead(401, { 'Content-Type': 'application/json' });
                    res.end(JSON.stringify({ message: '用户不存在' }));
                    return;
                }

                // 验证密码
                const isValidPassword = await bcrypt.compare(password, user.password);
                if (!isValidPassword) {
                    res.writeHead(401, { 'Content-Type': 'application/json' });
                    res.end(JSON.stringify({ message: '密码错误' }));
                    return;
                }

                // 生成JWT令牌
                const token = jwt.sign({ userId: user._id }, JWT_SECRET, { expiresIn: '24h' });

                // 返回用户信息和令牌
                res.writeHead(200, { 'Content-Type': 'application/json' });
                res.end(JSON.stringify({
                    token,
                    user: {
                        _id: user._id,
                        username: user.username,
                        email: user.email,
                        carbonFootprint: user.carbonFootprint,
                        greenEnergy: user.greenEnergy,
                        achievements: user.achievements,
                        tasks: user.tasks,
                        planetState: user.planetState
                    }
                }));
            } catch (error) {
                console.error('登录失败:', error);
                res.writeHead(500, { 'Content-Type': 'application/json' });
                res.end(JSON.stringify({ message: '登录失败，请重试' }));
            }
        });
        return;
    }

    // 处理登录请求之前添加注册请求处理
    if (parsedUrl.pathname === '/api/auth/register' && req.method === 'POST') {
        let body = '';
        req.on('data', chunk => {
            body += chunk.toString();
        });

        req.on('end', async () => {
            try {
                const userData = JSON.parse(body);

                // 检查邮箱是否已存在
                const existingUser = await User.findOne({ email: userData.email });
                if (existingUser) {
                    res.writeHead(400, { 'Content-Type': 'application/json' });
                    res.end(JSON.stringify({ message: '该邮箱已被注册' }));
                    return;
                }

                // 对密码进行加密
                const salt = await bcrypt.genSalt(10);
                const hashedPassword = await bcrypt.hash(userData.password, salt);

                // 创建新用户
                const newUser = new User({
                    ...userData,
                    password: hashedPassword
                });

                // 保存用户到数据库
                await newUser.save();

                // 生成JWT令牌
                const token = jwt.sign({ userId: newUser._id }, JWT_SECRET, { expiresIn: '24h' });

                // 返回用户信息和令牌
                res.writeHead(200, { 'Content-Type': 'application/json' });
                res.end(JSON.stringify({
                    token,
                    user: {
                        _id: newUser._id,
                        username: newUser.username,
                        email: newUser.email,
                        carbonFootprint: newUser.carbonFootprint,
                        greenEnergy: newUser.greenEnergy,
                        achievements: newUser.achievements,
                        tasks: newUser.tasks,
                        planetState: newUser.planetState
                    }
                }));
            } catch (error) {
                console.error('注册失败:', error);
                res.writeHead(500, { 'Content-Type': 'application/json' });
                res.end(JSON.stringify({ message: '注册失败，请重试' }));
            }
        });
        return;
    }

    // 处理任务详情请求
    if (parsedUrl.pathname.match(/^\/api\/tasks\/[^/]+\/details$/)) {
        try {
            const taskId = parsedUrl.pathname.split('/')[3];
            const task = await Task.findById(taskId);

            if (!task) {
                res.writeHead(404, { 'Content-Type': 'application/json' });
                res.end(JSON.stringify({ error: '任务不存在' }));
                return;
            }

            res.writeHead(200, { 'Content-Type': 'application/json' });
            res.end(JSON.stringify(task));
        } catch (error) {
            console.error('获取任务详情失败:', error);
            res.writeHead(500, { 'Content-Type': 'application/json' });
            res.end(JSON.stringify({ error: '获取任务详情失败' }));
        }
        return;
    }



    // 处理完成任务请求
    if (parsedUrl.pathname.match(/^\/api\/tasks\/[^/]+\/complete$/) && req.method === 'POST') {
        let body = '';
        req.on('data', chunk => {
            body += chunk.toString();
        });

        req.on('end', async () => {
            try {
                const taskId = parsedUrl.pathname.split('/')[3];
                const { userId } = JSON.parse(body);

                // 查找任务
                const task = await Task.findById(taskId);
                if (!task) {
                    res.writeHead(404, { 'Content-Type': 'application/json' });
                    res.end(JSON.stringify({ message: '任务不存在' }));
                    return;
                }

                // 查找用户
                const user = await User.findById(userId);
                if (!user) {
                    res.writeHead(404, { 'Content-Type': 'application/json' });
                    res.end(JSON.stringify({ message: '用户不存在' }));
                    return;
                }

                // 创建完成任务记录
                const completedTask = new CompleteTask({
                    title: task.title,
                    description: task.description,
                    category: task.type === 'environmental' ? '环保任务' : '个性化挑战',
                    userId: userId, // 添加用户ID
                    reward: {
                        greenEnergy: task.reward.greenEnergy,
                        carbonReduction: task.reward.carbonReduction,
                        waterQuality: task.reward.waterQuality || 0
                    },
                    finishAt: new Date()
                });

                // 保存完成的任务
                await completedTask.save();

                // 更新用户的绿色能量
                user.greenEnergy = (user.greenEnergy || 0) + task.reward.greenEnergy;
                await user.save();

                // 返回更新后的用户数据
                res.writeHead(200, { 'Content-Type': 'application/json' });
                res.end(JSON.stringify({
                    greenEnergy: user.greenEnergy,
                    message: '任务完成，绿色能量已更新'
                }));
            } catch (error) {
                console.error('完成任务失败:', error);
                res.writeHead(500, { 'Content-Type': 'application/json' });
                res.end(JSON.stringify({ message: '完成任务失败，请重试' }));
            }
        });
        return;
    }

    // 处理任务列表请求
    if (parsedUrl.pathname === '/api/tasks') {
        try {
            const carbonFootprint = parseInt(parsedUrl.query.carbonFootprint);
            let query = {};

            if (!isNaN(carbonFootprint)) {
                if (carbonFootprint > 30) {
                    query.category = { $in: ['base', 'high'] };
                } else if (carbonFootprint < 15) {
                    query.category = { $in: ['base', 'low'] };
                } else {
                    query.category = 'base';
                }
            }

            const tasks = await Task.find(query);
            res.writeHead(200, { 'Content-Type': 'application/json' });
            res.end(JSON.stringify(tasks));
        } catch (error) {
            console.error('获取任务失败:', error);
            res.writeHead(500, { 'Content-Type': 'application/json' });
            res.end(JSON.stringify({ error: '获取任务失败' }));
        }
        return;
    }

    // 处理环保任务请求
    if (parsedUrl.pathname === '/api/tasks/environmental') {
        try {
            // 查询类型为environmental的任务
            const environmentalTasks = await Task.find({ type: 'environmental' });

            res.writeHead(200, { 'Content-Type': 'application/json' });
            res.end(JSON.stringify(environmentalTasks));
        } catch (error) {
            console.error('获取环保任务失败:', error);
            res.writeHead(500, { 'Content-Type': 'application/json' });
            res.end(JSON.stringify({ error: '获取环保任务失败' }));
        }
        return;
    }


});

const PORT = 3001;
server.listen(PORT, () => {
    console.log(`后端服务器运行在 http://localhost:${PORT}`);
});


